package com.common.filter;

import com.common.context.UserContext;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 路亚
 * @version 0.1
 * @className UserInfoInterceptor
 * @description
 * @date 2024/12/12 20:51
 * @since jdk11
 */
public class UserInfoInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1.获取头信息中的用户信息
        String userId = request.getHeader("user_id");
        // 2.判断是否为空
        if (userId == null) {
            return true;
        }
        // 3.转为用户id并保存到ThreadLocal中
        try {
            UserContext.setCurrentId(Long.valueOf(userId));
            return true;
        } catch (NumberFormatException e) {
            return true;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 清理用户信息
        UserContext.removeCurrentId();
    }
}
